package com.platform.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.github.binarywang.wxpay.bean.coupon.WxPayCouponSendRequest;
import com.github.binarywang.wxpay.bean.coupon.WxPayCouponSendResult;
import com.github.binarywang.wxpay.bean.marketing.FavorCouponsCreateRequest;
import com.github.binarywang.wxpay.bean.marketing.FavorCouponsCreateResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author Admin
 */
@Slf4j
@Component
public class SendCouponWxService {

    @Value("${wx.pay.mchId}")
    String mchId;

    @Value("${wx.pay.creatorMchId}")
    String creatorMchId;

    @Autowired
    private WxMpService wxMpService;

//    @Autowired
//    CashCouponsService couponsService;

    @Autowired
    private WxPayService wxPayService;




    /**
     *
     * @param openId    微信用户唯一id
     * @param stockId   卡券批次id
     * @param requestNo  请求订单号。现使用卡券的id
     * @return
     */
    public JSONObject sendCouponV3(String openId, String stockId,String requestNo ) {
        JSONObject js = new JSONObject();
        try {

            FavorCouponsCreateRequest favorCouponsCreateRequest = new FavorCouponsCreateRequest();
            favorCouponsCreateRequest.setStockId(stockId);
            favorCouponsCreateRequest.setOutRequestNo(requestNo);
            favorCouponsCreateRequest.setStockCreatorMchid(mchId);
            favorCouponsCreateRequest.setAppid(wxMpService.getWxMpConfigStorage().getAppId());
            FavorCouponsCreateResult result = wxPayService.getMarketingFavorService().createFavorCouponsV3(openId, favorCouponsCreateRequest);
            String couponId = result.getCouponId();

            js.put("couponId",couponId);
            return js;
        } catch (WxPayException e) {
            e.printStackTrace();
            log.error("卡券发送错误，避免网络问题，不直接返回异常");
        }
        return js;
    }
}
